const sha1 = require('sha1');
const wxconifg = require('./../wechat/config');
const path = require('path');
const fs = require('fs');
const FormData = require('form-data');


const auth = ctx => {

  /**
   微信服务器GET请求携带的参数
   - signature 微信加密签名
   - timestamp 时间戳
   - nonce 随机数
   - echostr 随机字符串
   */
  const { signature, timestamp, nonce, echostr } = ctx.query;

  /**
   本地验证
   */
  const local_signature = sha1([wxconifg.token, timestamp, nonce].sort().join(''));
  return local_signature === signature ? echostr : '';
}

const getRealType = obj => Object.prototype.toString.call(obj).replace(/(^\[object )|(\]$)/g, '').toLowerCase();

const formatJson =result => {

  let message = void 0;

  try { result = JSON.parse(JSON.stringify(result)); }
  catch(err) { throw new Error(err); }

  if(Array.isArray(result)) {// array
    if(result.length === 1) {
      if(getRealType(result[0]) !== 'object' && !Array.isArray(result[0])) {// 非plain-object，非array
        message = result[0];
      } else {
        message = formatJson(result[0]);
      }
    } else {
      message = [];
      for(const val of result) {
        message.push(formatJson(val));
      }
    }
  } else if(getRealType(result) === 'object') {// plain-object
    message = {};
    for(const key in result) {// 遍历键
      if(getRealType(result[key]) !== 'object'
        && !Array.isArray(result[key])) {// 其它类型
        message[key] = result[key];
      } else {
        message[key] = formatJson(result[key]);
      }
    }
  } else {// 其它类型直接返回
    message = result;
  }
  return message;
}

const getFileForm = async file => {

  const form = new FormData();
  const reader = fs.createReadStream(file.path);
  form.append('media', reader, file.name);
  const headers = await new Promise((resolve, reject) => {
    form.getLength((err, length)=>{
      if(err) reject(err);
      resolve(Object.assign({ 'Content-Length': length }, form.getHeaders()));
    });
  });

  return { form, headers }
}

module.exports = {
  getRealType,
  formatJson,
  auth,
  getFileForm
}